package com.tjl.controller;

import com.tjl.model.Adver;
import com.tjl.service.Impl.AdverServiceImpl;
import com.tjl.util.CodeMsg;
import com.tjl.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author TJL
 * @date 2022/6/27
 */
@RestController
@RequestMapping("/advers")
public class AdverController {

    @Autowired
    private AdverServiceImpl adverService;

    @Autowired
    private JwtUtils jwtUtils;


    @GetMapping
    public CodeMsg getAll(){
        return new CodeMsg(adverService.list());
    }

    @PostMapping
    public CodeMsg add(@RequestHeader String token, @RequestBody Adver adver){
        Claims claims;
        try {
            claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"token异常");
        }
        return new CodeMsg(adverService.save(adver));
    }

    @PutMapping
    public CodeMsg put(@RequestHeader String token, @RequestBody Adver adver){
        Claims claims;
        try {
            claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"token异常");
        }
        return new CodeMsg(adverService.updateById(adver));
    }

    @DeleteMapping("/{id}")
    public CodeMsg delete(@PathVariable Integer id,@RequestHeader String token){
        Claims claims;
        try {
            claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"token异常");
        }
        return new CodeMsg(adverService.removeById(id));
    }
}
